type ArticleDataType = {
  [channel_id: number]: {
    pre_timestamp: string;
    results: ArticleType[];
  };
};

export type ArticleDetailType = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
};

const initialState = {
  articleData: {} as ArticleDataType,
  detail: {} as ArticleDetailType,
};

export type ArticleType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: {
    type: number;
    images: string[];
  };
};

export type ActionType =
  | {
      type: 'article/saveList';
      payload: { channel_id: number; pre_timestamp: string; results: ArticleType[] };
    }
  | {
      type: 'article/updateListById';
      payload: { channel_id: number; pre_timestamp: string; results: ArticleType[] };
    }
  | { type: 'article/saveDetail'; payload: ArticleDetailType };
export default function articleReducer(
  state = initialState,
  action: ActionType
): typeof initialState {
  switch (action.type) {
    case 'article/saveList':
      return {
        ...state,
        articleData: {
          ...state.articleData,
          [action.payload.channel_id]: {
            results: action.payload.results,
            pre_timestamp: action.payload.pre_timestamp,
          },
        },
      };

    case 'article/updateListById':
      const oldList = state.articleData[action.payload.channel_id].results;
      const newList = [...oldList, ...action.payload.results];
      return {
        ...state,
        articleData: {
          [action.payload.channel_id]: {
            pre_timestamp: action.payload.pre_timestamp,
            results: newList,
          },
        },
      };

    case 'article/saveDetail':
      return {
        ...state,
        detail: { ...action.payload },
      };
    default:
      return state;
  }
}
